<template>
  <div class="h100 tableSearchListFlexPage" style="padding-top:15px">
    <a-form layout="vertical" >
      <a-row :gutter="[16, 0]" style="margin-bottom: 20px">
        <!-- 品牌-->
        <a-col :span="4">
          <a-form-model-item :label="$t('品牌')">
            <a-select
              v-model="queryParam.company"
              @change="refreshData(true)"
              optionFilterProp="children"
              :filterOption="$commonFun.filterOption"
              showSearch
              placeholder="品牌"
              allow-clear
              style="width:100%"
            >
              <a-select-option
                v-for="item in allCompany"
                :key="item.id"
                :value="item.value"
                :title="item.name"
              >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item label="车型">
            <car-model-code-select
              mode="default"
              placeholder="请选择车型"
              :query="{ time:instantUpdateTime, selectAll: false}"
              :has-all="false"
              :clear="true"
              v-model="queryParam.modelCode"
              @changeoption="(val,item) => {queryParam.modelName = item ? item.showName : undefined;refreshData(true)}"
              style="width:100%"
            ></car-model-code-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item label="VIN">
            <a-input v-model="queryParam.vin" :placeholder="$t('pleaseInput') + 'VIN'" @keyup.enter="refreshData(true)" allow-clear :maxLength="17"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item label="ICCID">
            <a-input v-model="queryParam.iccId" :placeholder="$t('pleaseInput') + 'ICCID'" @keyup.enter="refreshData(true)" allow-clear/>
          </a-form-model-item>
        </a-col>
        <!-- 智驾域版本 -->
        <a-col :span="4">
          <a-form-model-item :label="$t('smartDrivingDomainVersion')">
            <a-input v-model="queryParam.vehicleVersion" :placeholder="$t('pleaseInput') + $t('smartDrivingDomainVersion')" @keyup.enter="refreshData(true)" allow-clear/>
          </a-form-model-item>
        </a-col>
        <!-- 车辆版本 -->
        <!-- <a-col :span="4">
          <a-form-model-item :label="$t('车辆版本')">
            <a-input v-model="queryParam.gcyVehicleVersion" :placeholder="$t('pleaseInput') + '车辆版本'" @keyup.enter="refreshData(true)" :maxLength="20"/>
          </a-form-model-item>
        </a-col> -->
        <!-- DILINK版本 -->
        <a-col :span="4">
          <a-form-model-item :label="$t('DILINK版本')">
            <a-input v-model="queryParam.dilinkVersion" :placeholder="$t('pleaseInput') + 'DILINK版本'" @keyup.enter="refreshData(true)" allow-clear/>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item :label="$t('生产车系')">
            <a-input v-model="queryParam.productionSeries" placeholder="生产车系" @keyup.enter="refreshData(true)" allow-clear/>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item :label="$t('生产车型')">
            <a-input v-model="queryParam.productionModel" placeholder="生产车型" @keyup.enter="refreshData(true)"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item :label="$t('公告车型')">
            <a-input v-model="queryParam.publishCode" placeholder="公告车型" @keyup.enter="refreshData(true)" allow-clear/>
          </a-form-model-item>
        </a-col>
        <!-- 创建人 -->
        <a-col :span="4">
          <a-form-model-item label="创建人">
            <a-select
              v-model="queryParam.createBy"
              showSearch
              allow-clear
              optionFilterProp="children"
              @change="refreshData(true)"
              :filterOption="$commonFun.filterOption"
              :placeholder="$t('pleaseSelect')+ '创建人'"
              :maxTagCount="1"
              style="width:100%"
            >
              <a-select-option
                v-for="(item,index) in userList"
                :key="'user'+index"
                :value="item.id"
                :title="item.name"
              >
                {{ item.name + '('+item.account+')' }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <!-- 使用方 -->
        <a-col :span="4">
          <a-form-model-item label="使用方">
            <!--<a-input v-model="queryParam.user" :placeholder="$t('pleaseInput') + '使用方'" @keyup.enter="refreshData(true)"/>-->
            <a-select
              v-model="queryParam.user"
              optionFilterProp="children"
              :filterOption="$commonFun.filterOption"
              showSearch
              :placeholder="$t('pleaseInput') + '使用方'"
              allow-clear
              @change="refreshData(true)"
              style="width:100%">
              <a-select-option
                key="0"
                value="规划院,工程院"
                title="规划院,工程院">
                规划院,工程院
              </a-select-option>
              <a-select-option
                key="1"
                value="规划院"
                title="规划院">
                规划院
              </a-select-option>
              <a-select-option
                key="2"
                value="工程院"
                title="工程院">
                工程院
              </a-select-option>
              <a-select-option
                key="3"
                value=""
                title="无">
                无
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item label="使用状态">
            <a-select
              v-model="queryParam.status"
              optionFilterProp="children"
              :filterOption="$commonFun.filterOption"
              showSearch
              :placeholder="$t('pleaseInput') + '使用状态'"
              allow-clear
              @change="refreshData(true)"
              style="width:100%"
            >
              <a-select-option
                :key="2"
                :value="2"
                title="使用中">
                使用中
              </a-select-option>
              <a-select-option
                :key="1"
                :value="1"
                title="可使用">
                可使用
              </a-select-option>
              <a-select-option
                :key="0"
                :value="0"
                title="不可用">
                不可用
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item label="创建时间">
            <a-range-picker
              v-model="queryParam.createTime"
              @change="(date,dateString) => {
                queryParam.createTimeStart = dateString[0] ;
                queryParam.createTimeEnd = dateString[1] ;
                refreshData(true)}"
              :show-time="{
                hideDisabledOptions: true,
                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
              }"
              style="width: 100%"
              :placeholder="['创建时间-开始','结束']"/>
          </a-form-model-item>
        </a-col>
        <!-- 数据来源-->
        <a-col :span="4">
          <a-form-model-item :label="$t('数据来源')">
            <a-select
              v-model="queryParam.dataFrom"
              @change="refreshData(true)"
              optionFilterProp="children"
              :filterOption="$commonFun.filterOption"
              showSearch
              placeholder="数据来源"
              allow-clear
              style="width:100%"
            >
              <a-select-option
                v-for="(item, index) in configModelDataFrom"
                :key="'dataFrom'+index"
                :value="item.value"
                :title="item.name"
              >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="4">
          <a-form-model-item :label="$t('生产日期')">
            <a-range-picker
              v-model="queryParam.produceTime"
              @change="(date,dateString) => {
                queryParam.produceTimeStart = dateString[0] ;
                queryParam.produceTimeEnd = dateString[1] ;
                refreshData(true)}"
              format="YYYY-MM-DD"
              style="width: 100%"
              :placeholder="['生产日期-开始','结束']"/>
          </a-form-model-item>
        </a-col>
        <a-col span="8">
          <div class="searchBtns" style="margin: 22px 0 0 0;">
            <a-button-group>
              <auth-button type="primary" :auth="managePerms.vehicle2.testView" @click="refreshData(true)">
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="() => { selectedRows=[];selectedRowKeys=[];queryParam = {};refreshData(true)}">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <auth-button :auth="managePerms.vehicle2.testAdd" @click="handleAddEdit">
              <i class="iconfont icon-xinjian"></i>
              {{ $t('new') }}
            </auth-button>
          </div>
        </a-col>
      </a-row>
    </a-form>
    <s-table
      ref="table"
      class="h100"
      size="default"
      rowKey="id"
      :columns="columns"
      :row-selection="{ selections:true,selectedRowKeys:selectedRowKeys, onChange: onTableSelectChange }"
      :data="loadData"
      :getPopupContainer="$commonFun.getPopupContainer"
      :scrollX="1900">
      <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
        <table-ellipsis :text="text || '-'" :key="column.key"></table-ellipsis>
      </template>
      <template slot="vin" slot-scope="text, record">
        <a @click="handleDetail(text)">
          <table-ellipsis :text="text"></table-ellipsis>
        </a>
      </template>
      <template slot="subModelCode" slot-scope="text, record">
        <table-ellipsis :text="record.modelStyleVo?record.modelStyleVo.code || '-':'-'"></table-ellipsis>
      </template>
      <template slot="makeYear" slot-scope="text, record">
        <table-ellipsis :text="record.modelStyleVo?record.modelStyleVo.makeYear || '-':'-'"></table-ellipsis>
      </template>
      <template slot="offLineTime" slot-scope="text, record">
        <table-ellipsis
          :text="text ? $options.filters.moment(text) : '-'">
        </table-ellipsis>
      </template>
      <template slot="status" slot-scope="text,record">
        <a v-if="record.taskOccupied==true && text == 1" @click="showUsingTask(record)">使用中</a>
        <table-ellipsis v-if="text == 0" text="不可用"></table-ellipsis>
        <table-ellipsis v-if="record.taskOccupied==false && text == 1" text="可使用"></table-ellipsis>
      </template>
      <span slot="operation" slot-scope="text, record" class="tableOperateSty">
        <template>
          <span style="display: flex;">

          <auth-button style="margin-right: 8px;" :auth="managePerms.vehicle2.testAdd" @click="copy(record)" type="primary" :ghost="true" size="small"><i class="iconfont icon-fuzhi"/>{{ $t('copy') }}</auth-button>

          <auth-button :disabled="(record.carAuditStatus===0) || (record.carAuditStatus===1) || (record.taskOccupied===true&&record.status===1)" style="margin-right: 8px;" :auth="managePerms.vehicle2.testEdit" @click="handleAddEdit('edit',record.id)" type="primary" :ghost="true" size="small"><i class="iconfont icon-xiugai"/>{{ $t('edit') }}</auth-button>

          <auth-button :disabled="(record.carAuditStatus===0) || (record.carAuditStatus===1) || (record.taskOccupied===true&&record.status===1)" style="margin-right: 8px;" :auth="managePerms.vehicle2.testDelete" @click="isEnabled('delete', record.id, record)" type="danger" :ghost="true" size="small"><i class="iconfont icon-shanchu3 deleteUlr"/>{{ $t('delete') }}</auth-button>

          <auth-button :disabled="(record.carAuditStatus===0) || (record.carAuditStatus===1) || (record.taskOccupied===true&&record.status===1)" v-if="record.status===1" :auth="managePerms.vehicle2.stop" @click="isEnabled('stop',record.id, record)" type="danger" :ghost="true" size="small"><a-icon type="stop"/>{{ $t('stop') }}</auth-button>

          <auth-button :disabled="(record.carAuditStatus===0) || (record.carAuditStatus===1) || (record.taskOccupied===true&&record.status===1)" v-if="record.status===0" :auth="managePerms.vehicle2.recovery" @click="isEnabled('recovery',record.id, record)" type="primary" :ghost="true" size="small"><a-icon type="check"/>{{ $t('recovery') }}</auth-button>
          <auth-button :auth="managePerms.vehicle2.testProfileDetails" @click="showProfileDetails(record)" type="primary" :ghost="true" size="small">{{ '档案详情' }}</auth-button>
          </span>
        </template>
      </span>
    </s-table>
    <import-car-model v-model="importVisible" :cols="importCols"/>
    <tasks-in-vehicle-dialog 
      @releaseok="refreshData"
      ref="tasksInVehicleDialog"
      :query="tasksInVehicleQuery"></tasks-in-vehicle-dialog>
  </div>
</template>
<script>
import FilterBoxCollection from '@/components/SelfComponents/FilterBoxCollection'
import CarModelSearch from './components/CarModelSearch.vue'
import CarModelList from './components/CarModelList.vue'
import CarModelStatistics from './components/CarModelStatistics.vue'
import EditTestCarModel from './components/EditTestCarModel'
import ImportCarModel from './components/ImportCarModel'
import CarModelBaseInfo from './components/CarModelBaseInfo'
import CarModelDetail from './components/CarModelDetail'
import {STable} from '@/components'
import {minxinDrawerUse} from '@/utils/mixin'
import AuthButton from '@/components/AuthButton'
import AuthText from '@/components/AuthText'
import {mapState} from 'vuex'
import {managePerms} from '@/config/permission/index'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import CarModelSelect from '@/views/components/CarModelSelect'
import {testVehicleColumns, importColumns} from './config/list.js'
import moment from 'moment'
import vehicleApi from '@/api/modules/system/vehicleMana'
import {downloadBlobFile} from '@/utils/functions'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import VehicleTypeSelect from '@/views/components/VehicleTypeSelect'
import AuthSwitch from '@/views/vehicle/components/AuthSwitch.vue'
import TasksInVehicleDialog from '@/views/components/TasksInVehicle/dialog.vue'
import formalProfileDetails from './components/formalProfileDetails.vue'


let makeYearList=[];
for (var i = 0; i < 100; i++) {
  makeYearList.push('20' + (i+"").padStart(2, '0'))
}
export default {
  name: 'vehicleListTab',
  mixins: [minxinDrawerUse],
  components: {
    STable,
    FilterBoxCollection,
    AuthButton,
    AuthText,
    CarModelSearch,
    CarModelList,
    CarModelCodeSelect,
    CarModelSelect,
    CarModelStatistics,
    tableEllipsis,
    VehicleTypeSelect,
    EditTestCarModel,
    ImportCarModel,
    CarModelDetail,
    AuthSwitch,
    TasksInVehicleDialog,
    formalProfileDetails
  },
  created () {
    const actionObj = this.actions[this.$route.query.action]
    // 从别的页面跳转过来调用相应的功能
    if (actionObj && actionObj.method) {
      this[actionObj.method]()
    }
    this.$store.dispatch('getProducePhaseDictCodeData');
    this.$store.dispatch('getManufacturerDictCodeData');
    this.$store.dispatch('getConfigModelDataFromDictCodeData');
    this.$store.dispatch('getCompanyDictCodeData');
  },
  mounted () {
    this.getUsers()
  },
  computed: {
    ...mapState({
      rightDrawerEvent: (state) => state.vehicle.rightDrawerEvent,
      instantUpdateTime: (state) => state.app.instantUpdateTime,
      configModelDataFrom: (state) => state.dict.configModelDataFromDictCode,
      allCompany: (state) => state.dict.companyDictCode
    }),
    commonColumns () {
      return this.columns.filter(item => !item.special)
    }
  },
  data () {
    let importCols = [...testVehicleColumns];
    importCols.splice(10, 0, ...importColumns)
    importCols.splice(importCols.length - 4, 4);
    return {
      moment,
      managePerms,
      formTitle: '',
      exporting: false,
      importVisible: false,
      makeYearList: makeYearList,
      columns: [...testVehicleColumns],
      importCols,
      //列表数据
      tableData: [],
      //选中行数据
      selectedRows: [],
      selectedRowKeys: [],
      // 查询参数
      queryParam: {},
      actions: {
        // 创建车辆
        ccl: {
          method: 'handleAddEdit'
        },
        // 导入车辆
        drcl: {
          method: 'handleImportFile'
        }
      },
      syncloading: false,
      modeDisplay: true,
      platform: false,
      manage: 0,
      flowElementId: '',
      userIds: [],
      userNames: [],
      records: {},
      userList: [],
      tasksInVehicleQuery: null
    }
  },
  watch: {
  },
  methods: {
    // 查看当前车辆正在执行的任务列表
    showUsingTask (record) {
      this.tasksInVehicleQuery = {
        vehicleId: record.id
      }
      this.$nextTick(() => {
        this.$refs.tasksInVehicleDialog.toggleVisible(true)
      })
    },
    getTaskFlowDesinNodeDataNewly (val) {
      this.$api.getTaskFlowDesinNodeDataNewly(val).then((res) => {
        console.log(res.data)
        this.flowElementId = res.data[0].flowElementId
        this.userIds = [res.data[0].roleCandidates[0].candidateUserId]
        this.userNames = [res.data[0].roleCandidates[0].candidatesName]
      })
    },
    onTableSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRowKeys.map(item => {
        return this.tableData.find(row => row.id === item);
      }).filter(row => row)
    },
    copy (recordData = {}) {
      this.handleAddEdit('copy', '', recordData.id);
    },
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      // const JnqueryParam = vm.queryParam
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      JnqueryParam.modelIds = [JnqueryParam.modelId];
      this.tableData = [];
      this.selectedRows = [];
      this.selectedRowKeys = [];
      const apiPromise = vm.$api.getVehiclePageData({...parameter, ...JnqueryParam, vehicleType: 2});
      return new Promise((resolve, reject) => {
        return apiPromise.then((res) => {
          if (res.data) {
            this.tableData = res.data
          }
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    // 停用/恢复/删除
    isEnabled (sign, vehicleId, records) {
      const _this = this
      _this.records = records
      const buttons = this.getRightDrawerFooterButtons({
        method: (sign === 'stop' ? `DeactivateList` : sign === 'delete' ? 'deleteList' : 'recover'),
        callback () {
          _this.refreshData(false)
        }
      })
      const vars = { nowTime: Date.now(), sign, vehicleId, getTaskFlowDesinNodeDataNewly: _this.getTaskFlowDesinNodeDataNewly }
      this.showRightDrawer(EditTestCarModel, this.$t(sign === 'stop' ? 'stop' : sign === 'delete' ? 'delete' : 'recovery'), buttons, 'large', vars)
    },
    // 停用
    DeactivateList (data, sucCallback) {
      console.log('停用')
      if (!(this.records instanceof Array)) {
        this.records = [this.records]
      }
      this.$api.operateVehicle({ vehicleIds: this.records.map(record => record.id), carOperationEnum: 'STOP', candidates: { flowElementId: this.flowElementId, userIds: this.userIds, userNames: this.userNames }, ...data }).then(() => {
        this.$message.success('已申请停用流程，待审批')
        if (sucCallback && typeof sucCallback === 'function') {
          sucCallback()
        }
        this.refreshData(false)
        this.removeRightDrawer()
      })
    },
    // 恢复
    recover (data, sucCallback) {
      console.log('恢复')
      if (!(this.records instanceof Array)) {
        this.records = [this.records]
      }
      this.$api.operateVehicle({ vehicleIds: this.records.map(record => record.id), carOperationEnum: 'RESUME', candidates: { flowElementId: this.flowElementId, userIds: this.userIds, userNames: this.userNames }, ...data }).then(() => {
        this.$message.success('已申请恢复流程，待审批')
        if (sucCallback && typeof sucCallback === 'function') {
          sucCallback()
        }
        this.refreshData(false)
        this.removeRightDrawer()
      })
    },
    // 删除
    deleteList (data, sucCallback) {
      console.log('删除')
      if (!(this.records instanceof Array)) {
        this.records = [this.records]
      }
      this.$api.operateVehicle({ vehicleIds: this.records.map(record => record.id), carOperationEnum: 'DEL', candidates: { flowElementId: this.flowElementId, userIds: this.userIds }, ...data }).then(() => {
        this.$message.success('已申请删除流程，待审批')
        if (sucCallback && typeof sucCallback === 'function') {
          sucCallback()
        }
        this.refreshData(false)
        this.removeRightDrawer()
      })
    },
    refreshData (isToFirstPage = true) {
      const vm = this
      vm.$nextTick(() => {
        this.$refs.table.refresh(isToFirstPage)
      })
    },
    // 新建/编辑车辆
    handleAddEdit (sign, vehicleId, copyId = '') {
      const _this = this
      const buttons = this.getRightDrawerFooterButtons({
        key: vehicleId ? managePerms.vehicle2.testEdit : managePerms.vehicle2.testAdd,
        method: 'saveData',
        callback () {
          _this.refreshData(!vehicleId)
        }
      })
      const vars = { nowTime: Date.now(), vehicleId, copyId, getTaskFlowDesinNodeDataNewly: _this.getTaskFlowDesinNodeDataNewly, sign }
      if (!copyId && !vehicleId) {
        this.showRightDrawerNoReset(EditTestCarModel, this.$t(vehicleId ? 'edit' : 'new') , buttons, 'large', vars);
      } else {
        this.showRightDrawer(EditTestCarModel, this.$t(vehicleId ? 'edit' : 'new') , buttons, 'large', vars);
      }
    },
    handleDetail(vin) {
      // 获取当前车辆信息
      this.$store.dispatch('getVehicleInfoData', { vin: vin }).then(res => {
      }).catch((err) => {
        console.log(err)
      })
      this.showRightDrawer(CarModelBaseInfo, this.$t('detailVehicle') + '-' + vin, [], '400px', {
        className: {
          'vehicle-detail-standalone': true
        },
        vin,
        openType: 'test'
      })
    },
    saveData (data) {
      data.insertTime = new Date(data.insertTime).getTime()
      data.onLineTime = new Date(data.onLineTime).getTime()
      data.offLineTime = new Date(data.offLineTime).getTime()
      // 当审批用户未选择时，不调用接口
      if (data.candidates && data.candidates.length === 0 && data.sign === 0) {
        return
      }
      if (data.id) {
        return vehicleApi.editVehicle(data)
      }
      return vehicleApi.addVehicle(data)
    },
    getUsers () {
      this.$api.getUserPageData({pageSize:5000}).then(res => {
        this.userList = res.data;
        console.log(this.userList, 'this.userList')
      }).catch((e) => vm.$message.error("获取创建人信息失败！"))
    },
    // 查看档案详情
    showProfileDetails (record) {
      this.showRightDrawer(formalProfileDetails, '查看档案详情', [], '90%', { time: Date.now(), vehicleId: record.id, vin: record.vin, openType: 'test' })
    }
  }
}
</script>
<style lang="less" scoped>
@import url("./style/prodList.less");
.ant-select-selection--multiple {
    max-height: 33px;
    overflow-y: auto;
    overflow-x: hidden;
}
/deep/.ant-row{
  .ant-form-item{
    margin-bottom: 0;
  }
}
/deep/.ant-col{
  .ant-form-item-label{
    padding-bottom: 2px;
  }
}
</style>
